/*
 * ========================================================
 * Copyright(c) 2014 杭州龙骞科技-版权所有
 * ========================================================
 * 本软件由杭州龙骞科技所有, 未经书面许可, 任何单位和个人不得以
 * 任何形式复制代码的部分或全部, 并以任何形式传播。
 * 公司网址
 * http://www.hzdracom.com/
 * ========================================================
 */
package newui.activity;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.webkit.ConsoleMessage;
import android.webkit.JsPromptResult;
import android.webkit.JsResult;
import android.webkit.WebChromeClient;
import android.webkit.WebChromeClient.CustomViewCallback;
import android.webkit.WebResourceResponse;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.TextView;

import com.shwread.android.qysw.activity.BaseBusinessActivity;
import com.shwread.android.qysw10000243.R;
import com.shwread.android.ui.widget.LoadingView;

import logic.util.Util;
import logic.util.logutil.LogUtil;


/**
 * @Project： Shwread
 * @Title：CommonWebActivity
 * @Description：
 * @Author：wayne
 * @Date：2015年3月9日上午11:29:55
 */
public class EvaluateWebActivity extends BaseBusinessActivity implements OnClickListener {

    private WebView webView = null;
    private WebChromeClient chromeClient = null;
    private View myView = null; //全频时View显示
    private TextView tvTitle = null;
    private Button btnBack = null;
    private FrameLayout fLayWebView = null;
    private View rlayTitle = null;
    private CustomViewCallback myCallBack = null;
    private LoadingView loadingView = null;


    private String mTitle = "";
    private String mUrl = "";

    /**
     * 应用是否退出
     */

    @Override
    public Handler getUIHandler() {
        return null;
    }

    @Override
    protected void onPause() {
        super.onPause();
//        webView.pauseTimers();
        if (isFinishing()) {
            webView.loadUrl("about:blank");
            setContentView(new FrameLayout(this));
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        webView.resumeTimers();
    }


    @Override
    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        setContentView(R.layout.webview_lay);
        Intent intent = getIntent();
        mTitle = intent.getStringExtra("title");
        mUrl = "http://122.224.254.133:2012/m_index.dll";
        initView();
        initLoadingView();
        setListener();
        setWebView();

        if (savedInstanceState != null) {
            webView.restoreState(savedInstanceState);
        }

    }

    @Override
    protected void onDestroy() {
        finish();
        super.onDestroy();
    }

    void initView() {
        fLayWebView = (FrameLayout) findViewById(R.id.webview_flay);
        webView = (WebView) findViewById(R.id.webview_web);
        tvTitle = (TextView) findViewById(R.id.common_header_name);
        tvTitle.setText(mTitle);
        btnBack = (Button) findViewById(R.id.common_header_back);
        btnBack.setVisibility(View.VISIBLE);
        rlayTitle = findViewById(R.id.common_title_layout);
        loadingView = (LoadingView) findViewById(R.id.webview_loading_view);
    }

    private void initLoadingView() {
        loadingView.setLoadingAnim(R.drawable.home_progress);
        //		loadingView.setLoadingAnim(R.anim.column_switch_anim);
        loadingView.changeLoadingStatus(0);

        loadingView.setVisibility(View.VISIBLE);
        /** 用GONE会导致部分视频加载不出来 */
        fLayWebView.setVisibility(View.INVISIBLE);
    }

    void setListener() {
        btnBack.setOnClickListener(this);
    }

    @SuppressLint("SetJavaScriptEnabled")
    void setWebView() {
        WebSettings webSeting = webView.getSettings();
        webSeting.setJavaScriptEnabled(true);
        webSeting.setJavaScriptCanOpenWindowsAutomatically(true);

        webView.setWebViewClient(new MyWebviewCient());

        chromeClient = new MyChromeClient();

        webView.setWebChromeClient(chromeClient);
        webSeting.setCacheMode(WebSettings.LOAD_NO_CACHE);
        webSeting.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.NARROW_COLUMNS);

        webView.setHorizontalScrollBarEnabled(false);
        webView.setVerticalScrollBarEnabled(true);
        webSeting.setSupportZoom(false);
        webSeting.setPluginState(WebSettings.PluginState.ON);
        webSeting.setLoadWithOverviewMode(true);
        webSeting.setUseWideViewPort(true); //适应屏幕

        if (Util.isEmpty(mUrl)) {
            loadingView.setVisibility(View.GONE);
            fLayWebView.setVisibility(View.VISIBLE);
        } else {
            webView.loadUrl(Util.addUrlTimestamp(mUrl));
        }

//        addJavaScriptMap(new SubMaintenanceJavaScriptInterface(), "qyreader");
    }


    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if(keyCode == KeyEvent.KEYCODE_BACK && webView.canGoBack()){
            finish();
            return true;
        }
        return super.onKeyDown(keyCode,event);
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        webView.saveState(outState);
    }

//    public void addJavaScriptMap(Object obj, String objName) {
//        webView.addJavascriptInterface(obj, objName);
//    }

    public class MyWebviewCient
            extends
            WebViewClient {
        @Override
        public WebResourceResponse shouldInterceptRequest(WebView view, String url) {
            WebResourceResponse response = null;
            response = super.shouldInterceptRequest(view, url);
            return response;
        }

        /*
         * 点击页面的某条链接进行跳转的话，会启动系统的默认浏览器进行加载，调出了我们本身的应用
         * 因此，要在shouldOverrideUrlLoading方法中
         */
        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            //使用当前的WebView加载页面
            if (url.contains("tel:")) {
                Intent intent = new Intent();
                intent.setAction(Intent.ACTION_DIAL);
                intent.setData(Uri.parse(url));
                startActivity(intent);
                return true;
            }
            view.loadUrl(url);
            return true;
        }

        /*
         * 网页加载完毕(仅指主页，不包括图片)
         */
        @Override
        public void onPageStarted(WebView view, String url, Bitmap favicon) {
            super.onPageStarted(view, url, favicon);
        }

        /*
         * 网页加载完毕(仅指主页，不包括图片)
         */
        @Override
        public void onPageFinished(WebView view, String url) {
            super.onPageFinished(view, url);
            loadingView.setVisibility(View.GONE);
            fLayWebView.setVisibility(View.VISIBLE);
        }

        /*
         * 加载页面资源
         */
        @Override
        public void onLoadResource(WebView view, String url) {
            super.onLoadResource(view, url);
        }

        /*
         * 错误提示
         */
        @Override
        public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
            LogUtil.e("webview", description);
            super.onReceivedError(view, errorCode, description, failingUrl);
            loadingView.setVisibility(View.GONE);
            fLayWebView.setVisibility(View.VISIBLE);
        }

    }

    public class MyChromeClient
            extends
            WebChromeClient {

        @Override
        public void onShowCustomView(View view, CustomViewCallback callback) {
            if (myView != null) {
                callback.onCustomViewHidden();
                return;
            }
            fLayWebView.removeView(webView);
            fLayWebView.addView(view);
            rlayTitle.setVisibility(View.GONE);
            myView = view;
            myCallBack = callback;
            setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_SENSOR);
        }

        @Override
        public void onHideCustomView() {
            if (myView == null) {
                return;
            }
            fLayWebView.removeView(myView);
            myView = null;
            setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
            fLayWebView.addView(webView);
            rlayTitle.setVisibility(View.VISIBLE);
            myCallBack.onCustomViewHidden();
        }

        @Override
        public boolean onConsoleMessage(ConsoleMessage consoleMessage) {
            Log.d("ZR", consoleMessage.message() + " at " + consoleMessage.sourceId() + ":" + consoleMessage.lineNumber());
            return super.onConsoleMessage(consoleMessage);
        }

        /*
         * 此处覆盖的是javascript中的alert方法。
         * 当网页需要弹出alert窗口时，会执行onJsAlert中的方法
         * 网页自身的alert方法不会被调用。
         */
        @Override
        public boolean onJsAlert(WebView view, String url, String message, JsResult result) {
            /*
			 * 此处代码非常重要，若没有，android就不能与js继续进行交互了，
			 * 且第一次交互后，webview不再展示出来。
			 * result：A JsResult to confirm that the user hit enter.
			 * 我的理解是，confirm代表着此次交互执行完毕。只有执行完毕了，才可以进行下一次交互。
			 */
            result.confirm();
            return true;
        }

        /*
         * 此处覆盖的是javascript中的confirm方法。
         * 当网页需要弹出confirm窗口时，会执行onJsConfirm中的方法
         * 网页自身的confirm方法不会被调用。
         */
        @Override
        public boolean onJsConfirm(WebView view, String url, String message, JsResult result) {
            return true;
        }

        /*
         * 此处覆盖的是javascript中的confirm方法。
         * 当网页需要弹出confirm窗口时，会执行onJsConfirm中的方法
         * 网页自身的confirm方法不会被调用。
         */
        @Override
        public boolean onJsPrompt(WebView view, String url, String message, String defaultValue, JsPromptResult result) {
            return true;
        }

        /*
         * 如果页面被强制关闭,弹窗提示：是否确定离开？
         * 点击确定 保存数据离开，点击取消，停留在当前页面
         */
        @Override
        public boolean onJsBeforeUnload(WebView view, String url, String message, JsResult result) {
            return true;
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.common_header_back:
                finish();
                break;
            default:
                break;
        }

    }


    final class SubMaintenanceJavaScriptInterface {

        /**
         * 在屏幕下端提示用户
         */
        public void setBookInfo(String bookId, String bookName, String bookType) {
            LogUtil.d("--", "bookId：" + bookId + " | bookName:" + bookName + " |bookType:" + bookType);
        }

        /**
         * 提供给B端打印日志
         */
        public void fireLog(String log) {
            LogUtil.d("dddd", log);
        }

        /**
         * 假如有历史记录 回退历史记录 否则退出容器
         */
        public void goBack() {
            BaseBusinessActivity.uiHandler.post(new Runnable() {
                @Override
                public void run() {
                    onBackPressed();
                }
            });
        }
    }

}
